package cn.topcodes.tcsf.wechat.web.controller;

import cn.topcode.unicorn.utils.JsonUtil;
import cn.topcodes.tcsf.admin.commons.api.controller.admin.AdminController;
import cn.topcodes.tcsf.admin.commons.api.domain.ApiResponseEntity;
import cn.topcodes.tcsf.wechat.domain.entity.WechatPicture;
import cn.topcodes.tcsf.wechat.domain.form.WechatPictureForm;
import cn.topcodes.tcsf.wechat.domain.vo.WechatPictureVo;
import cn.topcodes.tcsf.wechat.service.WechatFileService;
import cn.topcodes.tcsf.wechat.service.WechatPictureService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;

/**
 * @author xw
 * @date 2017-12-22 15:15:53
 */
@Controller
@RequestMapping("/admin/wechat/picture")
public class WechatPictureController extends AdminController<WechatPicture, WechatPictureVo, WechatPictureForm> {

    @Autowired
    private WechatPictureService wechatPictureService;

    @Autowired
    private WechatFileService wechatFileService;

    @Override
    protected String getPageFolder() {
        return "wechat/admin/material/picture";
    }

    @RequestMapping(value = "upload", method = RequestMethod.POST)
    public String upload(@RequestParam String mpId, MultipartFile file) {
        String name = file.getOriginalFilename();
        String pictureSavePath = wechatFileService.getPictureStoragePath();
        File pictureFile = new File(pictureSavePath);
        if (!pictureFile.exists()) {
            pictureFile.mkdirs();
        }
        pictureFile = new File(pictureSavePath, name);
        try {
            if (!pictureFile.exists()) {
                pictureFile.createNewFile();
            } else {
                pictureFile =
                        wechatFileService.createFile(pictureSavePath, wechatFileService.getSuffix(name));
            }
            file.transferTo(pictureFile);
            wechatPictureService.upload(mpId, pictureFile);
        } catch (Exception e) {
            if (pictureFile.exists()) {
                pictureFile.delete();
            }
            e.printStackTrace();
        }
        return "redirect:/admin/wechat/picture";
    }

    @Override
    @ResponseBody
    public String update(@RequestParam Long id, HttpServletRequest request, Model model) {
        WechatPicture picture = wechatPictureService.findOne(id);
        String name = request.getParameter("name");
        picture.setName(name);
        wechatPictureService.update(picture);
        return JsonUtil.toJson(ApiResponseEntity.buildOK());
    }
}
